package servlet;

import model.Goods;
import model.Order;
import service.GoodsService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "GoodsBuyServlet",urlPatterns = "/goods_buy")
public class GoodsBuyServlet extends HttpServlet {
    private GoodsService gService = new GoodsService();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        1.声明车
           Order o = null;
//        2.第一次没有车 创建
//        第二次有了 获取
//        页面 请求 会话 应用服务器     会话

        if (request.getSession().getAttribute("order")!=null){
            o =(Order) request.getSession().getAttribute("order");
        }else{
            o = new Order();
        }
        request.getSession().setAttribute("order",o);
//        3.获取前台参数goosid 查询商品信息
        int goodsid = Integer.parseInt(request.getParameter("goodsid"));
        Goods goods = gService.getGoodsById(goodsid);

//        4.加入购物车 库存问题
        if (goods.getStock()>0){
            o.addGoods(goods);
            response.getWriter().print("ok");

        }else{
            response.getWriter().print("fail");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
    }
}
